package com.library.borrow.servlet;

import com.alibaba.fastjson.JSON;
import com.library.borrow.model.BorrowRecord;
import com.library.borrow.service.BorrowRecordService;
import com.library.borrow.service.BorrowRecordServiceImpl;
import com.library.util.PageModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Calendar;

@WebServlet(value="*.borrow")
public class BorrowRecordServlet extends HttpServlet {
    private BorrowRecordService borrowRecordService = new BorrowRecordServiceImpl();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        String pathInfo = request.getPathInfo();
        
        // 检查并更新逾期状态
        borrowRecordService.checkAndUpdateOverdueStatus();
        
        // 查询单条借阅记录
        if (pathInfo != null && !pathInfo.equals("/")) {
            String[] splits = pathInfo.split("/");
            if (splits.length > 1) {
                Integer recordId = Integer.parseInt(splits[1]);
                BorrowRecord record = borrowRecordService.getBorrowRecordById(recordId);
                if (record != null) {
                    result.put("code", 200);
                    result.put("message", "获取借阅记录成功");
                    result.put("data", record);
                } else {
                    result.put("code", 404);
                    result.put("message", "借阅记录不存在");
                }
            }
        } else {
            // 检查是否是分页查询请求
            String pageNoStr = request.getParameter("pageNo");
            if (pageNoStr != null && !pageNoStr.isEmpty()) {
                // 分页查询处理
                queryByPage(request, response);
                return;
            }
            
            // 传统查询方式的处理
            String bookId = request.getParameter("bookId");
            String readerName = request.getParameter("readerName");
            String status = request.getParameter("status");
            String comingDueDays = request.getParameter("comingDueDays");
            
            List<Map<String, Object>> records = null;
            
            // 根据条件查询
            if (bookId != null && !bookId.isEmpty()) {
                records = borrowRecordService.getBorrowRecordsByBookId(Integer.parseInt(bookId));
            } else if (readerName != null && !readerName.isEmpty()) {
                records = borrowRecordService.getBorrowRecordsByReaderName(readerName);
            } else if (status != null && !status.isEmpty()) {
                records = borrowRecordService.getBorrowRecordsByStatus(status);
            } else if (comingDueDays != null && !comingDueDays.isEmpty()) {
                // 查询即将到期的借阅记录
                records = borrowRecordService.getComingDueBorrowRecords(Integer.parseInt(comingDueDays));
            } else {
                // 无条件查询所有借阅记录
                records = borrowRecordService.getAllBorrowRecords();
            }
            
            result.put("code", 200);
            result.put("message", "获取借阅记录列表成功");
            result.put("data", records);
        }
        
        out.write(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    /**
     * 分页查询借阅记录
     */
    private void queryByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        // 获取分页参数
        String pageNoStr = request.getParameter("pageNo");
        String pageSizeStr = request.getParameter("pageSize");
        String likeValue = request.getParameter("likeValue");
        
        // 设置分页模型
        PageModel pageModel = new PageModel();
        
        // 设置当前页码
        int pageNo = 1;
        if (pageNoStr != null && !pageNoStr.isEmpty()) {
            try {
                pageNo = Integer.parseInt(pageNoStr);
            } catch (NumberFormatException e) {
                // 解析异常，使用默认值
            }
        }
        pageModel.setPageNo(pageNo);
        
        // 设置每页记录数
        if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
            try {
                int pageSize = Integer.parseInt(pageSizeStr);
                pageModel.setPageSize(pageSize);
            } catch (NumberFormatException e) {
                // 解析异常，使用默认值
            }
        }
        
        // 设置查询条件
        pageModel.setLikeValue(likeValue);
        
        // 执行分页查询
        List<Map<String, Object>> records = borrowRecordService.getBorrowRecordsByPage(pageModel);
        
        // 设置查询结果
        pageModel.setRecordList(records);
        
        // 返回JSON结果
        out.write(JSON.toJSONString(pageModel));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求的URI，判断是否是特殊请求
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith("/return.borrow")) {
            // 处理归还图书请求
            handleReturnBook(request, response);
            return;
        } else if (requestURI.endsWith("/add.borrow")) {
            // 处理添加借阅请求
            handleAddBorrow(request, response);
            return;
        }
        
        // 原有的借阅记录创建逻辑
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 读取请求体数据
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        
        // 解析JSON为BorrowRecord对象
        Map<String, Object> recordMap = JSON.parseObject(sb.toString(), Map.class);
        BorrowRecord record = new BorrowRecord();
        record.setBookId(Integer.parseInt(recordMap.get("book_id").toString()));
        record.setReaderName((String) recordMap.get("reader_name"));
        record.setReaderPhone((String) recordMap.get("reader_phone"));
        
        // 解析借阅日期和应还日期
        String borrowDateStr = (String) recordMap.get("borrow_date");
        if (borrowDateStr != null && !borrowDateStr.isEmpty()) {
            try {
                record.setBorrowDate(sdf.parse(borrowDateStr));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        
        String returnDateStr = (String) recordMap.get("return_date");
        if (returnDateStr != null && !returnDateStr.isEmpty()) {
            try {
                record.setReturnDate(sdf.parse(returnDateStr));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        
        // 创建借阅记录
        boolean success = borrowRecordService.borrowBook(record);
        if (success) {
            result.put("code", 200);
            result.put("message", "借书成功");
        } else {
            result.put("code", 500);
            result.put("message", "借书失败，可能图书不存在或已被借出");
        }
        
        out.write(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    /**
     * 处理归还图书的请求
     */
    private void handleReturnBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查是否需要重定向到特定页面
        String returnPage = request.getParameter("returnPage");
        boolean needRedirect = returnPage != null && !returnPage.isEmpty();
        
        // 如果不需要重定向，设置JSON响应
        if (!needRedirect) {
            response.setContentType("application/json;charset=UTF-8");
        }
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        boolean success = false;
        
        try {
            // 获取借阅ID - 尝试多种可能的参数名
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.isEmpty()) {
                idStr = request.getParameter("borrowId");
            }
            if (idStr == null || idStr.isEmpty()) {
                idStr = request.getParameter("recordId");
            }
            
            // 如果仍然没有找到ID
            if (idStr == null || idStr.isEmpty()) {
                result.put("code", 400);
                result.put("message", "缺少借阅记录ID");
                if (!needRedirect) {
                    out.write(JSON.toJSONString(result));
                } else {
                    response.sendRedirect(returnPage + "?error=missing_id");
                }
                return;
            }
            
            Integer recordId = Integer.parseInt(idStr);
            
            // 获取归还日期
            Date actualReturnDate = null;
            String actualReturnDateStr = request.getParameter("actualReturnDate");
            if (actualReturnDateStr == null || actualReturnDateStr.isEmpty()) {
                actualReturnDateStr = request.getParameter("actual_return_date");
            }
            
            if (actualReturnDateStr != null && !actualReturnDateStr.isEmpty()) {
                try {
                    actualReturnDate = sdf.parse(actualReturnDateStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                    actualReturnDate = new Date(); // 如果解析失败，使用当前日期
                }
            } else {
                actualReturnDate = new Date(); // 默认使用当前日期
            }
            
            // 调用服务执行归还操作
            success = borrowRecordService.returnBook(recordId, actualReturnDate);
            if (success) {
                result.put("code", 200);
                result.put("message", "图书归还成功");
            } else {
                result.put("code", 500);
                result.put("message", "图书归还失败，可能借阅记录不存在或状态错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "归还图书时发生错误: " + e.getMessage());
        }
        
        // 根据结果决定是返回JSON还是重定向
        if (needRedirect) {
            if (success) {
                response.sendRedirect(returnPage + "?message=return_success");
            } else {
                response.sendRedirect(returnPage + "?error=return_failed");
            }
        } else {
            out.write(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }

    /**
     * 处理添加借阅的请求
     */
    private void handleAddBorrow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查是否需要重定向到特定页面
        String returnPage = request.getParameter("returnPage");
        boolean needRedirect = returnPage != null && !returnPage.isEmpty();
        
        // 如果不需要重定向，设置JSON响应
        if (!needRedirect) {
            response.setContentType("application/json;charset=UTF-8");
        }
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        boolean success = false;
        
        try {
            // 从表单参数获取数据
            String bookIdStr = request.getParameter("bookId");
            String readerName = request.getParameter("borrowerName");
            String readerPhone = request.getParameter("borrowerPhone");
            String borrowDateStr = request.getParameter("borrowDate");
            String returnDateStr = request.getParameter("returnDate");
            
            // 验证必要参数
            if (bookIdStr == null || bookIdStr.isEmpty()) {
                result.put("code", 400);
                result.put("message", "缺少图书ID");
                if (!needRedirect) {
                    out.write(JSON.toJSONString(result));
                } else {
                    response.sendRedirect(returnPage + "?error=missing_book_id");
                }
                return;
            }
            
            if (readerName == null || readerName.isEmpty()) {
                result.put("code", 400);
                result.put("message", "缺少借阅者姓名");
                if (!needRedirect) {
                    out.write(JSON.toJSONString(result));
                } else {
                    response.sendRedirect(returnPage + "?error=missing_reader_name");
                }
                return;
            }
            
            // 创建借阅记录对象
            BorrowRecord record = new BorrowRecord();
            record.setBookId(Integer.parseInt(bookIdStr));
            record.setReaderName(readerName);
            record.setReaderPhone(readerPhone);
            
            // 解析借阅日期
            if (borrowDateStr != null && !borrowDateStr.isEmpty()) {
                try {
                    record.setBorrowDate(sdf.parse(borrowDateStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                    record.setBorrowDate(new Date()); // 如果解析失败，使用当前日期
                }
            } else {
                record.setBorrowDate(new Date()); // 默认使用当前日期
            }
            
            // 解析应还日期
            if (returnDateStr != null && !returnDateStr.isEmpty()) {
                try {
                    record.setReturnDate(sdf.parse(returnDateStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                    // 默认设置为借阅日期后14天
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(record.getBorrowDate());
                    calendar.add(Calendar.DATE, 14);
                    record.setReturnDate(calendar.getTime());
                }
            } else {
                // 默认设置为借阅日期后14天
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(record.getBorrowDate());
                calendar.add(Calendar.DATE, 14);
                record.setReturnDate(calendar.getTime());
            }
            
            // 执行借阅操作
            success = borrowRecordService.borrowBook(record);
            if (success) {
                result.put("code", 200);
                result.put("message", "借阅成功");
            } else {
                result.put("code", 500);
                result.put("message", "借阅失败，可能图书不存在或已被借出");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "添加借阅记录时发生错误: " + e.getMessage());
        }
        
        // 根据结果决定是返回JSON还是重定向
        if (needRedirect) {
            if (success) {
                response.sendRedirect(returnPage + "?message=borrow_success");
            } else {
                response.sendRedirect(returnPage + "?error=borrow_failed");
            }
        } else {
            out.write(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        String pathInfo = request.getPathInfo();
        if (pathInfo != null && !pathInfo.equals("/")) {
            String[] splits = pathInfo.split("/");
            if (splits.length > 1) {
                Integer recordId = Integer.parseInt(splits[1]);
                
                // 删除借阅记录
                boolean success = borrowRecordService.deleteBorrowRecord(recordId);
                if (success) {
                    result.put("code", 200);
                    result.put("message", "删除借阅记录成功");
                } else {
                    result.put("code", 500);
                    result.put("message", "删除借阅记录失败");
                }
            } else {
                result.put("code", 400);
                result.put("message", "无效的请求路径");
            }
        } else {
            result.put("code", 400);
            result.put("message", "无效的请求路径");
        }
        
        out.write(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        String pathInfo = request.getPathInfo();
        if (pathInfo != null && !pathInfo.equals("/")) {
            String[] splits = pathInfo.split("/");
            if (splits.length > 1) {
                Integer recordId = Integer.parseInt(splits[1]);
                
                // 读取请求体数据
                BufferedReader reader = request.getReader();
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                
                Map<String, Object> recordMap = JSON.parseObject(sb.toString(), Map.class);
                
                // 如果包含还书相关的标记，则处理还书
                if (recordMap.containsKey("return") && (Boolean) recordMap.get("return")) {
                    // 处理还书
                    Date actualReturnDate = null;
                    String actualReturnDateStr = (String) recordMap.get("actual_return_date");
                    if (actualReturnDateStr != null && !actualReturnDateStr.isEmpty()) {
                        try {
                            actualReturnDate = sdf.parse(actualReturnDateStr);
                        } catch (ParseException e) {
                            e.printStackTrace();
                            actualReturnDate = new Date(); // 如果解析失败，使用当前日期
                        }
                    } else {
                        actualReturnDate = new Date(); // 默认使用当前日期
                    }
                    
                    boolean success = borrowRecordService.returnBook(recordId, actualReturnDate);
                    if (success) {
                        result.put("code", 200);
                        result.put("message", "还书成功");
                    } else {
                        result.put("code", 500);
                        result.put("message", "还书失败，可能借阅记录不存在或状态错误");
                    }
                } else {
                    // 更新借阅记录的其他信息
                    BorrowRecord record = borrowRecordService.getBorrowRecordById(recordId);
                    if (record != null) {
                        if (recordMap.containsKey("book_id")) {
                            record.setBookId(Integer.parseInt(recordMap.get("book_id").toString()));
                        }
                        if (recordMap.containsKey("reader_name")) {
                            record.setReaderName((String) recordMap.get("reader_name"));
                        }
                        if (recordMap.containsKey("reader_phone")) {
                            record.setReaderPhone((String) recordMap.get("reader_phone"));
                        }
                        
                        // 解析日期
                        if (recordMap.containsKey("borrow_date")) {
                            String borrowDateStr = (String) recordMap.get("borrow_date");
                            if (borrowDateStr != null && !borrowDateStr.isEmpty()) {
                                try {
                                    record.setBorrowDate(sdf.parse(borrowDateStr));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        
                        if (recordMap.containsKey("return_date")) {
                            String returnDateStr = (String) recordMap.get("return_date");
                            if (returnDateStr != null && !returnDateStr.isEmpty()) {
                                try {
                                    record.setReturnDate(sdf.parse(returnDateStr));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        
                        if (recordMap.containsKey("actual_return_date")) {
                            String actualReturnDateStr = (String) recordMap.get("actual_return_date");
                            if (actualReturnDateStr != null && !actualReturnDateStr.isEmpty()) {
                                try {
                                    record.setActualReturnDate(sdf.parse(actualReturnDateStr));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        
                        if (recordMap.containsKey("status")) {
                            record.setStatus((String) recordMap.get("status"));
                        }
                        
                        boolean success = borrowRecordService.updateBorrowRecord(record);
                        if (success) {
                            result.put("code", 200);
                            result.put("message", "更新借阅记录成功");
                        } else {
                            result.put("code", 500);
                            result.put("message", "更新借阅记录失败");
                        }
                    } else {
                        result.put("code", 404);
                        result.put("message", "借阅记录不存在");
                    }
                }
            } else {
                result.put("code", 400);
                result.put("message", "无效的请求路径");
            }
        } else {
            result.put("code", 400);
            result.put("message", "无效的请求路径");
        }
        
        out.write(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
} 